package com.ruoyi.system.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysPostService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.Employee;
import com.ruoyi.system.service.IEmployeeService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

/**
 * 员工管理Controller
 * 
 * @author ruoyi
 * @date 2023-04-11
 */
@Controller
@RequestMapping("/system/employee")
public class EmployeeController extends BaseController
{
    private String prefix = "system/employee";

    @Autowired
    private IEmployeeService employeeService;

    @Autowired
    private ISysPostService postService;

    @Autowired
    private ISysDeptService deptService;


    @RequiresPermissions("system:employee:view")
    @GetMapping()
    public String employee()
    {
        return prefix + "/employee";
    }

    /**
     * 查询员工管理列表
     */
    @RequiresPermissions("system:employee:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(Employee employee)
    {
        startPage();
        List<Employee> list = employeeService.selectEmployeeList(employee);
        return getDataTable(list);
    }

    /**
     * 导出员工管理列表
     */
    @RequiresPermissions("system:employee:export")
    @Log(title = "员工管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(Employee employee)
    {
        List<Employee> list = employeeService.selectEmployeeList(employee);
        ExcelUtil<Employee> util = new ExcelUtil<Employee>(Employee.class);
        return util.exportExcel(list, "员工管理数据");
    }

    /**
     * 新增员工管理
     */
    @GetMapping("/add")
    public String add(ModelMap mmap)
    {
        mmap.put("posts", postService.selectPostAll());
        mmap.put("depts", deptService.selectDeptAll());
        return prefix + "/add";
    }

    /**
     * 新增保存员工管理
     */
    @RequiresPermissions("system:employee:add")
    @Log(title = "员工管理", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(Employee employee)
    {
        return toAjax(employeeService.insertEmployee(employee));
    }

    /**
     * 修改员工管理
     */
    @RequiresPermissions("system:employee:edit")
    @GetMapping("/edit/{employeeId}")
    public String edit(@PathVariable("employeeId") Long employeeId, ModelMap mmap)
    {
        Employee employee = employeeService.selectEmployeeByEmployeeId(employeeId);
        mmap.put("employee", employee);
        return prefix + "/edit";
    }

    /**
     * 修改保存员工管理
     */
    @RequiresPermissions("system:employee:edit")
    @Log(title = "员工管理", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(Employee employee)
    {
        return toAjax(employeeService.updateEmployee(employee));
    }

    /**
     * 删除员工管理
     */
    @RequiresPermissions("system:employee:remove")
    @Log(title = "员工管理", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(employeeService.deleteEmployeeByEmployeeIds(ids));
    }

    /**
     * 部门调动
     */
    @RequiresPermissions("system:employee:transferdept")
    @GetMapping("/transferdept/{employeeId}")
    public String transferdept(@PathVariable("employeeId") Long employeeId, ModelMap mmap)
    {
        Employee employee = employeeService.selectEmployeeByEmployeeId(employeeId);
        mmap.put("employee", employee);
//        mmap.put("dept", deptService.selectDeptByEmployeeId(employeeId));
        mmap.put("dept", deptService.selectDeptAll());
        return prefix + "/transferdept";
    }

    /**
     * 部门调动保存
     */
    @RequiresPermissions("system:employee:transferdept")
    @Log(title = "员工管理", businessType = BusinessType.UPDATE)
    @PostMapping("/transferdept")
    @ResponseBody
    public AjaxResult transferdeptSave(long employeeId,String dept) {return toAjax(employeeService.transferDeptByEmployeeId(employeeId,dept));}

    /**
     * 岗位调动
     */
    @RequiresPermissions("system:employee:transferpost")
    @GetMapping("/transferpost/{employeeId}")
    public String transferpost(@PathVariable("employeeId") Long employeeId, ModelMap mmap)
    {
        Employee employee = employeeService.selectEmployeeByEmployeeId(employeeId);
        mmap.put("employee", employee);
        mmap.put("post", postService.selectPostAll());
//        mmap.put("post", postService.selectPostByEmployeeId(employeeId));
        return prefix + "/transferpost";
    }

    /**
     * 岗位调动保存
     */
    @RequiresPermissions("system:employee:transferpost")
    @Log(title = "员工管理", businessType = BusinessType.UPDATE)
    @PostMapping("/transferpost")
    @ResponseBody
    public AjaxResult transferpostSave(long employeeId,String post) {return toAjax(employeeService.transferPostByEmployeeId(employeeId,post));}

//    /**
//     * 转正管理
//     */
//    @RequiresPermissions("system:employee:traineetoemployee")
//    @GetMapping("/traineetoemployee/{employeeId}")
//    public String traineetoemployee(@PathVariable("employeeId") Long employeeId, ModelMap mmap)
//    {
//        Employee employee = employeeService.selectEmployeeByEmployeeId(employeeId);
//        mmap.put("employee", employee);
//        return prefix + "/traineetoemployee";
//    }

    /**
     * 转正保存管理
     */
    @RequiresPermissions("system:employee:traineetoemployee")
    @Log(title = "员工管理", businessType = BusinessType.UPDATE)
    @PostMapping("/traineetoemployee")
    @ResponseBody
    public AjaxResult traineetoemployeeSave(long employeeId)
    {
        return toAjax(employeeService.TraineeToEmployee(employeeId));
    }

    /**
     * 上传档案
     */
    @RequiresPermissions("system:employee:uploadfiles")
    @GetMapping("/uploadfiles/{employeeId}")
    public String uploadfiles(@PathVariable("employeeId") Long employeeId, ModelMap mmap)
    {
        Employee employee = employeeService.selectEmployeeByEmployeeId(employeeId);
        mmap.put("employee", employee);
        return prefix + "/uploadfiles";
    }

    /**
     * 设置上传文件的最大值10M
     */
    public static final int FILES_MAX_SIZE=10*1024*1024;

//    /**
//     * 设置上传文件的类型
//     */
//    public static final List<String> FILES_TYPE=new ArrayList<>();
//    static {
//        FILES_TYPE.add("/pdf");
//        FILES_TYPE.add("/doc");
//        FILES_TYPE.add("/docx");
//    }

    /**
     * 上传档案保存
     */
    @RequiresPermissions("system:employee:uploadfiles")
    @Log(title = "员工管理", businessType = BusinessType.UPDATE)
    @PostMapping("/uploadfiles")
    @ResponseBody
    public AjaxResult uploadfilesSave(long employeeId, MultipartFile file) throws IOException {
//        if(file.isEmpty()){
//            return AjaxResult.error("文件为空");
//        }
        if(file.getSize()>FILES_MAX_SIZE){
            return AjaxResult.error("文件超出限制！");
        }
//        String contentType=file.getContentType();//文件类型
//        if(!FILES_TYPE.contains(contentType)){
//            return AjaxResult.error("文件类型不支持");
//        }
        //上传的文件.../upload/文件.png(获取当前项目的绝对磁盘路径)
//        String parent=session.getServletContext().getRealPath("upload");
        String parent = "D:\\EmployeeFiles\\upload";
        System.out.println(parent);
        //file对象指向这个路径，file是否存在
        File dir=new File(parent);
        if(!dir.exists()){
            dir.mkdirs();//创建当前目录
        }
        //获取文件的名称，UUID工具来将生成的新字符串作为文件名
        String originalFilename=file.getOriginalFilename();
        System.out.println("OriginalFilename="+originalFilename);
        int index=originalFilename.lastIndexOf(".");
        String suffix=originalFilename.substring(index);//文件后缀
        if((!suffix.equals(".pdf"))){
            return error("文件类型不支持！");
        }
        String filename= UUID.randomUUID().toString().toUpperCase()+suffix;
        File dest=new File(dir,filename);//空文件
        //参数file中数据写入到这个空文件中
        file.transferTo(dest);//将file文件中的数据写入到dest文件中
        //返回档案的名称
        String files = filename;
        employeeService.updateFilesByEmployeeId(employeeId, files);
        //返回档案的路径给前端页面
        return success("上传成功！");
    }

//    @RequiresPermissions("system:employee:downloadfiles")
//    @GetMapping("/downloadfiles")
//    @ResponseBody
//    public void downloadfiles(long employeeId, HttpServletRequest request, HttpServletResponse response) throws Exception {
//        //获得下载的资源文件夹
//        String fileName = employeeService.selectFilesByEmployeeId(employeeId);
//        String path = "D:\\employeefiles\\upload\\" + fileName;
////        String realPath = request.getRealPath("/upload");
//        //获得输入流
//        FileInputStream is = new FileInputStream(new File(path, fileName));
//        //获得输出流
//        ServletOutputStream os = response.getOutputStream();
//        //以附件的形式下载
//        response.setHeader("content-disposition","attachment;fileName="+ URLEncoder.encode(fileName,"UTF-8"));
//        IOUtils.copy(is,os);
//        IOUtils.closeQuietly(is);
//        IOUtils.closeQuietly(os);
//    }

    @RequiresPermissions("system:employee:downloadfiles")
    @GetMapping("/downloadfiles")
    @ResponseBody
    public void downloadfiles(String path, HttpServletResponse response) throws IOException {
//        String files = employeeService.selectFilesByEmployeeId(employeeId);
//        String path = "D:\\employeefiles\\upload\\" + files;
        // 读到流中
        InputStream inputStream = new FileInputStream(path);// 文件的存放路径
        response.reset();
        response.setContentType("application/octet-stream");
        String filename = new File(path).getName();
        response.addHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(filename, "UTF-8"));
        ServletOutputStream outputStream = response.getOutputStream();
        byte[] b = new byte[1024];
        int len;
        //从输入流中读取一定数量的字节，并将其存储在缓冲区字节数组中，读到末尾返回-1
        while ((len = inputStream.read(b)) > 0) {
            outputStream.write(b, 0, len);
        }
        inputStream.close();
    }

    /**
     * 请假时间
     */
    @RequiresPermissions("system:employee:leave")
    @GetMapping("/leave/{employeeId}")
    public String leave(@PathVariable("employeeId") Long employeeId, ModelMap mmap)
    {
        Employee employee = employeeService.selectEmployeeByEmployeeId(employeeId);
        mmap.put("employee", employee);
        return prefix + "/leave";
    }

    /**
     * 请假时间保存
     */
    @RequiresPermissions("system:employee:leave")
    @Log(title = "员工管理", businessType = BusinessType.UPDATE)
    @PostMapping("/leave")
    @ResponseBody
    public AjaxResult leave(Long employeeId, Date leaveTime, Date backTime) {
        return toAjax(employeeService.setLeaveBackTime(employeeId, leaveTime, backTime));
    }

//    @RequiresPermissions("system:employee:countemployeebydept")
//    @PostMapping("/countemployeebydept")
//    @ResponseBody
//    public AjaxResult countemployeebydept(){
//        List<Integer> list = new ArrayList<>();
//        list.add(employeeService.countEmployeeByDept("研发部门"));
//        list.add(employeeService.countEmployeeByDept("市场部门"));
//        list.add(employeeService.countEmployeeByDept("测试部门"));
//        list.add(employeeService.countEmployeeByDept("财务部门"));
//        list.add(employeeService.countEmployeeByDept("运维部门"));
//        return toAjax(list);
//
//    }

//    /**
//     * 查看档案
//     */
//    @RequiresPermissions("system:employee:viewfiles")
//    @PostMapping("/viewfiles")
//    @ResponseBody
//    public AjaxResult viewfiles(long employeeId)
//    {
//        return toAjax(employeeService.selectFilesByEmployeeId(employeeId));
//    }
}
